package xyz.xtt.admin.utils;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.json.JSONUtil;
import cn.idev.excel.FastExcel;
import cn.idev.excel.context.AnalysisContext;
import cn.idev.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Jim kwok
 * @since 2025/2/28
 */
@Slf4j
public class ExcelUtils {

    /**
     * 读取excel文件
     */
    public static <T> List<T> readExcel(MultipartFile file, final Class<T> clazz) {
        Assert.notNull(file);
        UploadDataListener<T> listener = new UploadDataListener<>();
        try {
            FastExcel.read(file.getInputStream(), clazz, listener).sheet().doRead();
        } catch (IOException e) {
            log.info("文件读取异常");
        }
        return listener.getRecords();
    }
}

@Slf4j
class UploadDataListener<T> extends AnalysisEventListener<T> {
    private final List<T> list = new ArrayList<>();

    @Override
    public void invoke(T record, AnalysisContext context) {
        String phone = JSONUtil.parseObj(record).get("phone").toString();
        boolean isPhone = PhoneUtil.isMobile(phone);
        if (isPhone) {
            list.add(record);
            return;
        }
        log.info("手机号码格式不正确, {}", phone);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("所有数据解析完成！总计：{}条数据", list.size());
    }

    public List<T> getRecords() {
        return list;
    }
}
